package com.hlg.xboot.utils;

import com.hlg.xboot.exceptions.APISignException;
import com.hlg.xboot.constants.AppConstants;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.TreeMap;

/**
 * <p>Description: 安全工具接口</p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 * <p>myblog: http://blog.csdn.net/xyang81</p>
 *
 * @author 杨信
 * @version 1.0
 * @date 2016/12/6
 */
public class SecurityUtils {

    private static final Logger logger = LoggerFactory.getLogger(SecurityUtils.class);

    public static String sign(Map<String,String[]> params) throws APISignException {
        if (params == null || !params.containsKey(AppConstants.PARAM_SIGN_NAME)) {
            return null;
        }

        // 1.按字典排序请求参数
        Map<String,String> map = new TreeMap<>();
        params.forEach((key, value) -> {
            if (!AppConstants.PARAM_SIGN_NAME.equals(key)) {
                map.put(key,value[0]);
            }
        });

        // 2.拼接参数
        StringBuffer sb = new StringBuffer();
        map.forEach((key, value) -> {
            sb.append(key).append("=").append(value).append("&");
        });
        sb.append(AppConstants.PARAM_SIGN_KEY);

        logger.debug("sign str: " + sb.toString());
        // 3.加密
        String expectSign = DigestUtils.md5Hex(sb.toString());

        return expectSign;

    }
}
